package com.yanyu.space.common.gateway.filter.support;

import com.yanyu.space.common.gateway.filter.LogFilter;
import com.yanyu.space.common.log.handler.LogFactory;
import com.yanyu.space.common.log.handler.LogWorkerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.sleuth.CurrentTraceContext;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.brave.bridge.BraveSpan;
import org.springframework.cloud.sleuth.instrument.web.WebFluxSleuthOperators;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.time.LocalDateTime;

/**
 * @author gz
 */
public class SleuthLogPrint implements ILogPrint {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogFilter.class);
    @Autowired
    private Tracer tracer;

    @Autowired
    private CurrentTraceContext currentTraceContext;

    @Override
    public void print(URI finalOriginUri, Route route, URI url, ServerWebExchange exchange) {
        WebFluxSleuthOperators.withSpanInScope(tracer,
                currentTraceContext,
                exchange,
                () -> {
                    try (LogWorkerContext logWorkerContext = LogFactory.getInstance().start(BraveSpan.toBrave(tracer.currentSpan()).context().traceIdString())) {
                        LOGGER.info("转发请求：{}://{}{} --> 目标服务：{}，目标地址：{}://{}{}，转发时间：{}",
                                finalOriginUri.getScheme(), finalOriginUri.getAuthority(), finalOriginUri.getPath(),
                                route.getId(), url.getScheme(), url.getAuthority(), url.getPath(), LocalDateTime.now()
                        );
                    }
                });
    }
}
